package com.lazason.wib4android;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.util.Linkify;
import android.text.util.Linkify.TransformFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.lazason.wib4android.AsyncImageLoader.ImageCallback;

public class MyAdapter extends SimpleAdapter {
	private String tag="MyAdapter";
	private int mResource;
	private LayoutInflater mInflater;
	private int[] mTo;
	private ViewBinder mViewBinder;
	private String[] mFrom;
	//private List<? extends Map<String, ?>> mData;
	private Context context;
	AsyncImageLoader asyncImageLoader;
	static Pattern userPattern = Pattern.compile("@(\\w+?)(?=\\W|$)");
	static String friendScheme = "wib://friendhomeactivity/?screen_name=";
	static DateFormat dateFormat= DateFormat.getDateInstance();

	public MyAdapter(Context context, List<? extends Map<String, ?>> data,
			int resource, String[] from, int[] to, ListView listView) {
		super(context, data, resource, from, to);
		this.context = context;
		//this.mData = data;
		this.mFrom = from;
		this.mTo = to;
		this.mResource = resource;
		mInflater = ((Activity) context).getLayoutInflater();
		asyncImageLoader = new AsyncImageLoader();
		// TODO Auto-generated constructor stub
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		return createViewFromResource(position, convertView, parent, mResource);
	}

	private View createViewFromResource(int position, View convertView,
			ViewGroup parent, int resource) {
		View v;
		if (convertView == null) {
			v = mInflater.inflate(resource, parent, false);

			final int[] to = mTo;
			final int count = to.length;
			final View[] holder = new View[count];

			for (int i = 0; i < count; i++) {
				holder[i] = v.findViewById(to[i]);
			}

			v.setTag(holder);
		} else {
			v = convertView;
		}

		bindView(position, v);

		return v;
	}

	private void bindView(int position, View view) {
		final Map dataSet = (Map)getItem(position);
		if (dataSet == null) {
			return;
		}
		final int pos = position;
		final ViewBinder binder = mViewBinder;
		final View[] holder = (View[]) view.getTag();
		final String[] from = mFrom;
		final int[] to = mTo;
		final int count = to.length;
        if(MyApplication.isWifi(context)){
        	if(dataSet.get("original_pic")!=null){
        		
        		asyncImageLoader
        		.preDownload(context, (String)dataSet.get("original_pic"), "op"+dataSet.get("original_pic").hashCode(),
        				Thread.MIN_PRIORITY);
        	}
        }
        if("night".equals(MyApplication.style)){
        	view.setBackgroundResource(R.color.black);
        	
        	
		} else {
			view.setBackgroundResource(R.color.white);
		}
		for (int i = 0; i < count; i++) {
			final View v = holder[i];
			
			if (v != null) {
				final Object data = dataSet.get(from[i]);
				String text = data == null ? "" : data.toString();
				if (text == null) {
					text = "";
				}

				boolean bound = false;
				if (binder != null) {
					bound = binder.setViewValue(v, data, text);
				}

				if (!bound) {
					if (v instanceof Checkable) {
						if (data instanceof Boolean) {
							((Checkable) v).setChecked((Boolean) data);
						} else {
							throw new IllegalStateException(v.getClass()
									.getName()
									+ " should be bound to a Boolean, not a "
									+ data.getClass());
						}
					} else if (v instanceof TextView) {
						// Note: keep the instanceof TextView check at the
						// bottom of these
						// ifs since a lot of views are TextViews (e.g.
						// CheckBoxes).
						if("night".equals(MyApplication.style)){
				        	((TextView)v).setTextColor(context.getResources().getColor(R.color.dark_gray));
				        	
						} else {
							((TextView)v).setTextColor(context.getResources().getColor(R.color.dim_gray));
							
						}
						
						if("retweetedText".equals(from[i])){
							if(text==null||((Map)getItem(pos)).get("retweetedUsername")==null){
								Log.d(tag, "retweetedUsername is null; text="+text);
								text = null;
							} else {
								text = "@"+(String) ((Map)getItem(pos)).get("retweetedUsername")+":"+text;
								 if("night".equals(MyApplication.style)){
							        	v.setBackgroundResource(R.color.dim_gray);
							        	
							        	
									} else {
										v.setBackgroundResource(R.color.light_gray);
									}
							}
					       
							 
							
						}
						setViewText((TextView) v, text);
						if("weibo".equals(from[i])||"retweetedText".equals(from[i])){
							if(text!=null&&text.indexOf("http")>=0){
								Linkify.addLinks((TextView) v, Linkify.WEB_URLS);
							}
							v.setOnClickListener(new OnClickListener() {
								String id = String.valueOf(((Map)getItem(pos)).get("id"));
								String screen_name = (String) ((Map)getItem(pos)).get("username");
								String description = (String) ((Map)getItem(pos)).get("description");
								String location = (String) ((Map)getItem(pos)).get("location");
								String big_profile = ((String) ((Map)getItem(pos)).get("profile")).replace("/50/", "/180/");

								@Override
								public void onClick(View arg0) {

									 
									Intent intent = new Intent();
									intent.putExtra("id", String.valueOf( ((Map)getItem(pos)).get("weibo_id")));
									intent.putExtra("username", (String) ((Map)getItem(pos)).get("username"));
									intent.putExtra("profile", (String) ((Map)getItem(pos)).get("profile"));
									intent.putExtra("created_at", Util.getCreatedAtString((Date) ((Map)getItem(pos)).get("created_at")));
									intent.putExtra("picture", (String) ((Map)getItem(pos)).get("picture"));
									intent.putExtra("weibo", (String) ((Map)getItem(pos)).get("weibo"));
									intent.putExtra("retweetedText", (String)((Map)getItem(pos)).get("retweetedText"));
									intent.putExtra("retweetedThumbnailPic", (String) ((Map)getItem(pos)).get("retweetedThumbnailPic"));
									intent.putExtra("retweetedUsername", (String) ((Map)getItem(pos)).get("retweetedUsername"));
									intent.setClass(context, PostCommentActivity.class);
									context.startActivity(intent); 
								}

							});
							Linkify.addLinks((TextView) v, userPattern, friendScheme, null,
									new TransformFilter() {
										@Override
										public String transformUrl(Matcher match, String url) {

											return match.group(1); // replace here with sina user
																	// lookup function
										}
									});
							
						}
						if("username".equals(from[i])){
						v.setOnClickListener(new OnClickListener() {
							String id = String.valueOf(((Map)getItem(pos)).get("id"));
							String screen_name = (String) ((Map)getItem(pos)).get("username");
							String description = (String) ((Map)getItem(pos)).get("description");
							String location = (String) ((Map)getItem(pos)).get("location");
							String big_profile = ((String) ((Map)getItem(pos)).get("profile")).replace("/50/", "/180/");
							@Override
							public void onClick(View arg0) {

								Intent intent = new Intent();
								intent.putExtra("id", id);
								intent.putExtra("screen_name", screen_name);
								intent.putExtra("description", description);
								intent.putExtra("location", location);
								intent.putExtra("big_profile", big_profile);
								intent.setClass(context, HomeActivity.class);
								((Activity) context).startActivity(intent);
							}

						});
						}
						if("created_at".equals(from[i])){
							long currentTime  = System.currentTimeMillis();
							if(((Map)getItem(pos)).get("created_at") instanceof Date){
							Date createdAt = (Date) ((Map)getItem(pos)).get("created_at");
							if(currentTime-createdAt.getTime()<60000){
								setViewText((TextView) v, (currentTime-createdAt.getTime())/1000+"秒前");
							} else if(currentTime-createdAt.getTime()<3600000){
								setViewText((TextView) v, (currentTime-createdAt.getTime())/60000+"分前");
							} else if(currentTime-createdAt.getTime()<86400000){
								setViewText((TextView) v, (currentTime-createdAt.getTime())/3600000+"小时前");
							} else if(currentTime-createdAt.getTime()<604800000){
								setViewText((TextView) v, (currentTime-createdAt.getTime())/86400000+"天前");
							} else {
								setViewText((TextView) v, dateFormat.format(createdAt));
							}
							}else {
								setViewText((TextView) v, ((Map)getItem(pos)).get("created_at").toString());
							}
						}
						if("comment_repost".equals(from[i])){
							int reposts = 0;
							int comments = 0;
							if(((Map)getItem(pos)).get("repost_count")!=null){
								  reposts = (Integer)((Map)getItem(pos)).get("repost_count");
							}
							if(((Map)getItem(pos)).get("comments_count")!=null){
								comments = (Integer)((Map)getItem(pos)).get("comments_count");
							}
							
							if(reposts+comments>0){
								setViewText((TextView) v, "转发（"+reposts+")"+"|评论("+comments+")");
							}
						}
					} else if (v instanceof ImageView) {
						if(!MyApplication.isWifi(context)&&"save".equals(MyApplication.saveMode)){
							((ImageView)v).setImageDrawable(null);
							continue;
						}
						if ("profile".equals(from[i])) {
							if(context instanceof FriendHomeActivity){
								((ImageView) v).setImageDrawable(null);
								continue;
							}
							String id = "pr" + String.valueOf(((Map)getItem(pos)).get("id"));
							v.setTag(id);
							Drawable cachedImage = asyncImageLoader
									.loadDrawable(context, (String) ((Map)getItem(pos)).get("profile"), id,
											Thread.MAX_PRIORITY,
											new ImageCallback() {
												public void imageLoaded(
														Drawable imageDrawable,
														String imageUrl,
														String id) {
													ImageView imageViewByTag = (ImageView) v.findViewWithTag(id);
													if (imageViewByTag != null
															&& imageDrawable != null) { // 防止图片url获取不到图片是，占位图片不见了的情况
														imageViewByTag
																.setImageDrawable(imageDrawable);

													}
												}
											});
							if (cachedImage == null) {
								// holder.profile.setImageResource(R.drawable.icon);
								((ImageView) v).setImageDrawable(null);
							} else {
								((ImageView) v).setImageDrawable(cachedImage);
							}
							v.setOnClickListener(new OnClickListener() {
								String id = String.valueOf(((Map)getItem(pos)).get("id"));
								String screen_name = (String) ((Map)getItem(pos)).get("username");
								String description = (String) ((Map)getItem(pos)).get("description");
								String location = (String) ((Map)getItem(pos)).get("location");
								String big_profile = ((String) ((Map)getItem(pos)).get("profile")).replace("/50/", "/180/");

								@Override
								public void onClick(View arg0) {

									Intent intent = new Intent();
									intent.putExtra("id", id);
									intent.putExtra("screen_name", screen_name);
									intent.putExtra("description", description);
									intent.putExtra("location", location);
									intent.putExtra("big_profile", big_profile);

									intent.setClass(context, HomeActivity.class);
									((Activity) context).startActivity(intent);
								}

							});
						} else if ("picture".equals(from[i])||"retweetedThumbnailPic".equals(from[i])) {
							String url  = String.valueOf(((Map)getItem(pos)).get(from[i]));
							if(url==null){
								((ImageView) v).setImageDrawable(null);
								continue;
							}
							
							String id = "pi" + url.hashCode();
							v.setTag(id);
							Drawable cachedImage = asyncImageLoader
									.loadDrawable(context, url, id,
											Thread.MAX_PRIORITY-2,
											new ImageCallback() {
												public void imageLoaded(
														Drawable imageDrawable,
														String imageUrl,
														String id) {
													ImageView imageViewByTag = (ImageView) v.findViewWithTag(id);
													if (imageViewByTag != null
															&& imageDrawable != null) { // 防止图片url获取不到图片是，占位图片不见了的情况
														imageViewByTag
																.setImageDrawable(imageDrawable);

													}
												}
											});
							if (cachedImage == null) {
								((ImageView) v).setImageDrawable(null);
							} else {
								((ImageView) v).setImageDrawable(cachedImage);
							}
							  String originalUrl = null;
							if("picture".equals(from[i])){
								originalUrl = (String)((Map)getItem(pos)).get("original_pic");
							} 
							else {
								originalUrl = (String)((Map)getItem(pos)).get("retweetedOriginalPic");
							}  
							if(originalUrl==null){
								continue;
							}
							final String url2 = originalUrl;
							final String originalId = "op" + originalUrl.hashCode();
							v.setOnClickListener(new OnClickListener() { 
								
								@Override
								public void onClick(View arg0) {
									Intent intent = new Intent();
									intent.putExtra("id", originalId);
									intent.putExtra("original_pic", url2);
									intent.setClass(context, ImageBrowserActivity.class);
									((Activity) context).startActivity(intent);
										   
								}

							});
						}
					} else {
						throw new IllegalStateException(
								v.getClass().getName()
										+ " is not a "
										+ " view that can be bounds by this SimpleAdapter");
					}
				}
			}
		}
	}

	@Override
	public void notifyDataSetChanged() {
		// TODO Auto-generated method stub
		super.notifyDataSetChanged();
	}
	
}
